package com.gitee.fanx.retty.spring.springmvc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.fanx.retty.web.Request;
import com.gitee.fanx.retty.spring.ParamResolver;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;

/**
 * @author fanhang
 */
public class RequestBodyResolver implements ParamResolver {
	private final boolean required;
	private final Class<?> clazz;
	private final ObjectMapper objectMapper;

	public RequestBodyResolver(RequestBody requestBody, Class<?> clazz, ObjectMapper objectMapper) {
		this.required = requestBody.required();
		this.clazz = clazz;
		this.objectMapper = objectMapper;
	}

	@Override
	public Object resolve(Request request) {
		Object result = null;
		try {
			result = objectMapper.readValue(request.body(), clazz);
		} catch (IOException e) {
			throw new IllegalStateException(e.getMessage());
		}
		if (result != null) {
			return result;
		}
		if (required) {
			throw new IllegalArgumentException("required body argument");
		}
		return null;
	}

	@Override
	public String toString() {
		return "RequestBody(" + clazz.getSimpleName() + ")";
	}

}
